<!--
 * @Descripttion: 
 * @Autor: zhouchen
 * @Date: 2020-12-21 18:49:14
 * @LastEditTime: 2021-08-12 16:05:56
-->

<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">转库单</p>
    <br />
    <a-form-model :model="queryform" v-bind="layout">
      <!-- 顶部的信息  -->

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="单据号">
          <div>{{ queryform.document }}</div>
        </a-form-model-item>
      </a-col>

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="单据日期">
          <div>{{ queryform.document_date }}</div>
        </a-form-model-item>
      </a-col>

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="出库仓库">
          <div>{{ queryform.outboundHouse }}</div>
        </a-form-model-item>
      </a-col>

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="入库仓库">
          <div>{{ queryform.inboundHouse }}</div>
        </a-form-model-item>
      </a-col>

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="收发类别">
          <div>{{ queryform.sarType }}</div>
        </a-form-model-item>
      </a-col>

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="公司">
          <div>{{ queryform.pkCorp_dictText }}</div>
        </a-form-model-item>
      </a-col>

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="库存组织">
          <div>{{ queryform.pkCalbody_dictText }}</div>
        </a-form-model-item>
      </a-col>

      <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="备注">
          <div>{{ queryform.headRemark }}</div>
        </a-form-model-item>
      </a-col>
    </a-form-model>

    <a-table
      :columns="columns"
      :data-source="data"
      style="margin-top: 10px"
      :pagination="false"
      :scroll="autoSize"
    ></a-table>

    <div style="margin-top: 20px">
      <!-- 单据 -->
      <a-form-model :model="queryform" v-bind="layout">
        <!-- 顶部的信息 -->
        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人">
              <div>{{ queryform.reviewer }}</div>
            </a-form-model-item>
          </a-col>

          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期">
              <div>{{ queryform.document_date }}</div>
            </a-form-model-item>
          </a-col>

          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人">
              <div>{{ queryform.single_producer }}</div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <!-- 提交按钮组  
      1. 能审核提交的人是不能点击保存的
      2. 能保存的人是不能审核和提交的
      -->
      <div style="margin-top: 20px">
        <center>
          <!-- <a-button type="primary" style="margin-right: 20px">打印</a-button> -->

          <a-button style="margin-right: 20px" disabled>保存</a-button>

          <a-button
            @click="Examine"
            style="margin-right: 20px"
            :disabled="!alreadyCheckTag"
            >审核</a-button
          >
          <a-button
            @click="Examine_otherSide"
            style="margin-right: 20px"
            :disabled="alreadyCheckTag"
            >反审核</a-button
          >

          <!-- <a-button
            type="primary"
            @click="Submit"
            style="margin-right: 20px"
            :disabled="!alreadyRecordTag"
            >提交</a-button
          > -->

          <a-button type="primary" @click="save_u8c" style="margin-right: 20px">
            同步至用友
          </a-button>
        </center>
      </div>
    </div>
  </a-card>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax();

import { ZhuanKu } from "@/services/modules/KuCunTiaoZheng/ZhuanKu.js";
const zhuankuHttp = new ZhuanKu();

import { ZhuanKuLieBiao } from "@/services/modules/KuCunTiaoZheng/ZhuanKuLieBiao.js";
const zhuankuliebiaoHttp = new ZhuanKuLieBiao();
import axios from "axios";

import moment from "moment";
import "moment/locale/zh-cn";

const columns = [
  {
    title: "序号",
    dataIndex: "lineNo",
    key: "lineNo",
    align: "center",
    width: 200,
  },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    scopedSlots: { customRender: "inventoryNo" },
    width: 200,
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
    width: 200,
  },
  {
    title: "规格型号",
    dataIndex: "specificationsModel",
    key: "specificationsModel",
    align: "center",
    width: 200,
  },
  {
    title: "单位",
    dataIndex: "unit",
    key: "unit",
    align: "center",
    width: 200,
  },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    width: 200,
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "金额",
    dataIndex: "amount",
    key: "amount",
    align: "center",
    width: 200,
    scopedSlots: { customRender: "amount" },
  },
  {
    title: "出库仓库",
    dataIndex: "dischargeHouse",
    key: "dischargeHouse",
    align: "center",
    scopedSlots: { customRender: "dischargeHouse" },
    width: 200,
  },
  {
    title: "出库库位",
    dataIndex: "outboundLocation",
    key: "outboundLocation",
    align: "center",
    scopedSlots: { customRender: "outboundLocation" },
    width: 200,
  },
  {
    title: "出库仓位",
    dataIndex: "dischargeBin",
    key: "dischargeBin",
    align: "center",
    scopedSlots: { customRender: "dischargeBin" },
    width: 200,
  },
  {
    title: "入库仓库",
    dataIndex: "receivingHouse",
    key: "receivingHouse",
    align: "center",
    scopedSlots: { customRender: "receivingHouse" },
    width: 200,
  },
  {
    title: "入库库位",
    dataIndex: "inboundLocation",
    key: "inboundLocation",
    align: "center",
    scopedSlots: { customRender: "inboundLocation" },
    width: 200,
  },
  {
    title: "入库仓位",
    dataIndex: "receivingBin",
    key: "receivingBin",
    align: "center",
    scopedSlots: { customRender: "receivingBin" },
    width: 200,
  },
  {
    title: "批次号",
    dataIndex: "batchNo",
    key: "batchNo",
    align: "center",
    scopedSlots: { customRender: "batchNo" },
    width: 200,
  },
  {
    title: "转库日期",
    dataIndex: "transferDate",
    key: "transferDate",
    align: "center",
    scopedSlots: { customRender: "transferDate" },
    width: 200,
  },
  {
    title: "备注",
    dataIndex: "remarks",
    key: "remarks",
    align: "center",
    scopedSlots: { customRender: "remarks" },
    width: 300,
  },
  {
    title: "操作",
    dataIndex: "options",
    key: "options",
    align: "center",
    scopedSlots: { customRender: "options" },
    width: 100,
  },
];

export default {
  data() {
    return {
      u8c_array: [], //u8c传递数据表格的数据源
      arr: [], //
      arrIn: [], //其他入库单
      GeneralBillVO_46: [], //需给用友传递的data
      GeneralBillVO_46In: [], //需给用友传递的data
      ayyanyany: [],
      ayyanyanyIn: [],
      totalData: [], //详情所有数据
      updateSucessRecordTag: false, //同步至u8c按钮的状态

      // 查询表单数据
      queryform: {
        document: "",
        document_date: "",
        outboundHouse: "",
        inboundHouse: "",
        sarType: "",
        headRemark: "",
        reviewer: "",
        single_producer: "",
        single_producer_id: "",
        balance: "",
      },

      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      columns,
      data: [],
      autoSize: {
        x: 3500,
        y: 670,
      },
      alreadyCheckTag: true, // 可以审核
      alreadyRecordTag: true, // 可以记账
    };
  },
  watch: {
    $route: function () {
      this.getRouterParam();
    },
  },

  mounted() {
    this.getRouterParam();
  },

  methods: {
    //反审核函数
    Examine_otherSide() {
      let data = {
        id: this.queryform.id,
        auditMark: 2, //Y 为 1，N 为 2
      };
      // 提交审核信息，修改表一数据
      zhuankuHttp.postUpdateWarhouseTransfer(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("反审核成功");
          this.$router.push({
            path: "RedepositList",
          });
        } else {
          this.$message.error("反审核失败");
        }
      });
    },
    // 获取存货编码和存货信息
    getInventoryCode() {
      let _list = [];
      return new Promise((resolve) => {
        comHttp.getInventoryInformation().then((res) => {
          let array = res.result;
          console.log("----- arrayIn -----", array);
          for (let i = 0; i < array.length; i++) {
            let singleData = {
              inventory_id: array[i].id,
              inventory_no: array[i].inventoryNo,
              inventory_name: array[i].inventoryName,
              specificationsModel: array[i].specificationsModel,
              unit: array[i].unit,
            };
            _list.push(singleData);
          }
        });
        resolve(_list);
      });
    },
    //是否同步标志位
    postSynchronized(isOrNo) {
      let data = {
        id: this.queryform.id,
        isSynchronized: isOrNo,
      };
      zhuankuHttp.postUpdateWarhouseTransfer(data).then((res) => {
        console.log(res);
      });
    },
    // 审核函数
    Examine() {
      this.queryform.balance = moment(this.queryform.document_date).format(
        "YYYY-MM-DD"
      );
      console.log(this.queryform.balance);
      let data = {
        id: this.queryform.id,
        auditMark: 1,
        balance: this.queryform.balance,
      };

      // 提交审核信息，修改表一数据
      zhuankuHttp.postUpdateWarhouseTransfer(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("审核成功");
          this.alreadyCheckTag = false;
          this.$router.push("/RedepositList");
        } else {
          this.$message.error("审核失败");
        }
      });
    },

    // 提交
    Submit() {
      let data = {
        id: this.queryform.id,
        bookkeepingMark: 1,
      };
      // 提交审核信息，修改表一数据
      zhuankuHttp.postUpdateWarhouseTransfer(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("记账成功");
          this.alreadyRecordTag = false;
        } else {
          this.$message.error("记账失败");
        }
      });
    },

    // 单据同步至u8c
    async save_u8c() {
      this.ayyanyany = [];
      console.log(
        "this.totalData.auditMark_dictText",
        this.totalData[0].auditMark_dictText
      );
      if (this.totalData[0].auditMark_dictText == "已审核") {
        for (let i = 0; i < this.u8c_array.length; i++) {
          console.log("i", i);

          this.arr = [];

          for (let j = 0; j < this.u8c_array[i].length; j++) {
            console.log("j", j);
            console.log("this.u8c_array[i].length", this.u8c_array[i].length);
            let data = {
              cinventoryid: this.u8c_array[i][j].inventoryNo, //存货id
              dshldtransnum: this.u8c_array[i][j].number, //应转数量
              pk_measdoc: this.u8c_array[i][j].shortname, //主计量单位
              crowno: (j + 1) * 10,
            };
            this.arr.push(data);
            console.log("this.arr", this.arr);
          }
          this.GeneralBillVO_46 = {
            parentvo: {
              cauditor: this.u8c_array[i][0].telPhonetwo, //审核人
              coperatorid: this.u8c_array[i][0].telPhoneone, //制单人id
              coutwarehouseid: this.u8c_array[i][0].outboundWarehouseIdCode, //出库仓库id
              cinwarehouseid: this.u8c_array[i][0].inWarehouseIdCode, //入库仓库id
              dbilldate: moment(this.u8c_array[i][0].documentDate).format(
                "YYYY-MM-DD"
              ), //订单日期
              // dauditdate: moment(this.u8c_array[i][0].transferDate).format("YYYY-MM-DD"),//签字日期
              vbillcode: this.u8c_array[i][0].document, //单据号
              // cdispatcherid: "2001", //收发类别id
              pk_calbody: "100001", //库存组织编码
              pk_corp: "1001", //公司编码
            },
            childrenvo: this.arr,
          };

          this.ayyanyany.push(this.GeneralBillVO_46);
        }
        // u8c新增接口
        let flag = await axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/ic/special4k/insert",
          data: {
            specialbillvo: this.ayyanyany,
          },
        }).then((response) => {
          console.log("返回的数据为::::", response.data);
          if (response.data.status == "success") {
            this.$message.success("转库单同步成功");
            this.updateSucessRecordTag = true;
            this.postSynchronized("已同步");
            this.$router.push("/RedepositList");
            return response.data.status;
          } else {
            this.$message.error(response.data.errormsg);
            return response.data.status;
          }
        });
        console.log("flag", flag);
        // if (flag == "falied") {
        //   this.$message.error("转库单同步失败！");
        // }
        if (flag == "success") {
          axios({
            headers: {
              "Access-Control-Allow-Origin": "*",
              trantype: "code",
              "Content-Type": "application/json",
              usercode: "13355262265",
              password: "5ef208ee90e5504a7b569ebbd6342634",
              system: "test",
            },
            method: "post",
            // url: "/proxy/u8cloud/api/ic/special4r/transferoutinsign",
            url: "/proxy/u8cloud/api/ic/special4k/transferoutinsign",

            data: {
              specialbillvo: this.ayyanyany,
            },
          }).then((response) => {
            console.log("返回的数据为::::", response.data);
            if (response.data.status == "success") {
              this.$message.success("同步成功");

              this.updateSucessRecordTag = true;
            } else {
              this.$message.error(response.data.errormsg);
            }
          });
        }
      } else {
        this.$message.error("请先进行审核，再同步至用友！");
      }
    },

    // 获取路由参数
    getRouterParam() {
      console.log("查询参数:::", this.$route.query.Id);
      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        console.log("常规跳转");
      } else {
        this.setInitInfo(this.$route.query.Id);
      }
    },

    // 根据路由传递id初始化表单信息
    setInitInfo(id) {
      let sub; // 是否可点击提交
      zhuankuliebiaoHttp
        .getWarehouseTransferList(`?id=${id}&pageSize=200&pageNo=1`)
        .then((res) => {
          console.log("----- routerListRes -----", res);
          let getData = res.result.records[0];
          if (getData.auditMark == 1) {
            this.alreadyCheckTag = false;
          } else {
            this.alreadyCheckTag = true;
          }
          sub = getData.bookkeepingMark;

          if (sub === 1) {
            this.alreadyCheckTag = true;
          }
          this.queryform.id = getData.id;
          this.queryform.document = getData.document;
          this.queryform.document_date = getData.documentDate;
          this.queryform.outboundHouse = getData.outboundWarehouseId_dictText;
          this.queryform.inboundHouse = getData.inWarehouseId_dictText;
          this.queryform.sarType = getData.category_dictText;
          this.queryform.remarks = getData.remark;
          this.queryform.reviewer = getData.reviewer_dictText; //审核人
          this.queryform.single_producer = getData.reparedBy_dictText; //制单人
          this.queryform.single_producer_id = getData.reparedBy;
          this.queryform.headRemark = getData.headRemark; //这是表头的备注
          this.queryform.pkCorp_dictText = getData.pkCorp_dictText; //这个是公司
          this.queryform.pkCalbody_dictText = getData.pkCalbody_dictText; //这个是库存组织
          this.queryform.pkCorp_dictText = getData.pkCorp_dictText;

          // 将数据赋值给表格
          let array = res.result.records;
          let resArray = [];
          for (let i = 0; i < array.length; i++) {
            let singleData = {
              key: i + 1,
              lineNo: i + 1,
              id: array[i].twoId, // id
              inventoryId: array[i].inventoryId, // 存货id
              inventoryNo: array[i].inventoryNo, // 存货编码
              inventoryName: array[i].inventoryId_dictText, // 存货名称
              specificationsModel: array[i].specificationsModel, // 规格型号
              unit: array[i].unit, //单位
              quantity: array[i].number, // 数量
              amount: array[i].money, // 金额
              dischargeHouse: array[i].outboundWarehouseId_dictText, // 出库仓库
              outboundLocation: array[i].outboundLocation_dictText, // 出库库位
              dischargeBin: array[i].outboundPosition_dictText, // 出库仓位
              receivingHouse: array[i].inWarehouseId_dictText, // 入库仓库
              inboundLocation: array[i].inboundLocation_dictText, // 入库库位
              receivingBin: array[i].inboundPosition_dictText, // 入库仓位
              batchNo: array[i].batchNo, // 批次号
              transferDate: array[i].documentDate, // 转库日期
              remarks: array[i].remark, // 备注
              goodsList: this.getInventoryCode(),
            };
            resArray.push(singleData);
          }

          this.data = resArray;
          this.sortArr(res.result.records, "dischargeHouse");
          this.totalData = res.result.records;
          console.log("this.totalData", this.totalData);
        });
    },

    // this.u8c_array数组根据仓库编码筛选，将相同的仓库编码放在一个数组里
    sortArr(arr, str) {
      var newArr = [],
        newArrItem = [],
        // 临时变量
        tempArr = [];
      // 按照特定的参数将数组排序将具有相同值的排在一起
      arr = arr.sort(function (a, b) {
        var s = a[str],
          t = b[str];

        return s < t ? -1 : 1;
      });

      if (arr.length) {
        tempArr = arr[0][str];
      }

      // 将相同类别的对象添加到统一个数组
      for (var i in arr) {
        if (arr[i][str] === tempArr) {
          console.log("tempArr", tempArr);
          newArrItem.push(arr[i]);
        } else {
          tempArr = arr[i][str];
          newArr.push(newArrItem);
          newArrItem = [arr[i]];
        }
      }

      // 将最后的内容推出新数组
      newArr.push(newArrItem);
      this.u8c_array = newArr;
      console.log("u8c_arr", this.u8c_array);
    },
  },
};
</script>

<style>
</style>
